<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/11/13 14:47
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\Api\V1\App\Customers;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Customers\CustomerLoginRequest;
use App\Models\Customers\Customer;
use App\Services\Customers\Login\LoginFactory;
use App\Services\EasySms\EasySmsService;
use Illuminate\Http\Request;

class CustomerLoginController extends ApiController
{
    /**
     * @param CustomerLoginRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function login(CustomerLoginRequest $request)
    {
        $service = LoginFactory::create($request->type);

        $login = $service->login($request);

        return $this->response(compact('login'));
    }

    /**
     * 微信授权登录
     *
     * @param Request $request
     */
    public function oauthWechat(Request $request)
    {
        $code = $request->code;

        $token_query = http_build_query([
            'appid'      => 'TODO store config appid',
            'secret'     => 'TODO store config secret',
            'code'       => $code,
            'grant_type' => 'authorization_code', // <- const
        ]);
        $token_api = "https://api.weixin.qq.com/sns/oauth2/access_token?$token_query";

        // try
        $data = json_decode(file_get_contents($token_api), true);

        // check data

        /*
         * $data = [
            "access_token"  => "ACCESS_TOKEN",
            "expires_in"    => 7200,
            "refresh_token" => "REFRESH_TOKEN",
            "openid"        => "OPENID",
            "scope"         => "SCOPE",
            "unionid"       => "o6_bmasdasdsad6_2sgVt7hMZOPfL",
            ];
        */
        $user_info_query = http_build_query([
            'access_token' => $data['access_token'],
        ]);
        // use access_token to request user info
        $user_info_api = "https://api.weixin.qq.com/sns/userinfo?$user_info_query";

        // try
        $user_info = json_decode(file_get_contents($user_info_api), true);
        // check data
        // Todo $user_info Example

        // update or create wechat_user in db by openid

        // check if wechat user had bound customer
        //
        // if bound return app login info and token
        //
        // if not bind
    }
}